﻿using Alison.EFCore;
using Alison.EFCore.Entity;
using Alison.Service.IService;
using Alison.Tools.HttpContact.Response;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Alison.Service.Service
{
    public class MqttMessageService : IMqttMessageService
    {
        private readonly ILogger<MqttMessageService> _logger;
        public MqttMessageService(ILogger<MqttMessageService> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<ApiResponse> GetAll(string type)
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = await db.Mqttmessages.Where(t=>t.Messagetype.Equals(type)).ToListAsync();

                return new ApiResponse(200, model.OrderBy(t => t.Id));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResponse> GetAll()
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = await db.Mqttmessages.ToListAsync();

                return new ApiResponse(200, model.OrderBy(t => t.Id));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }

        /// <summary>
        /// 添加消息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResponse> SendMessages(Mqttmessage dto)
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = await db.Mqttmessages.AddAsync(dto);
                var ok = await db.SaveChangesAsync();
                return new ApiResponse(200, ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }
    }
}
